﻿using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Wicture.DbRESTFul;

namespace Wicture.QPZS.EPC.Services.LiYang
{
    public class LiYangVinService
    {
        private readonly static string _appKey = ConfigurationManager.Settings.Variables["LiYang.AppKey"];
        private readonly static string _appSecret = ConfigurationManager.Settings.Variables["LiYang.AppSecret"];
        public static VinQueryResResult VinQuery(string vin)
        {
            VinQueryResResult result = null;
            try
            {
                string url = GetVinUrl(vin);
                WebClient wc = new WebClient();
                var html = wc.CrawHtml(url, "get", null, null);
                html = html.Trim(new char[] { '(', ')' });
                VinQueryRes ret = JsonConvert.DeserializeObject<VinQueryRes>(html);
                if (ret == null)
                {
                    throw new Exception("ret is null");
                }
                var retInfo = ret.Info;
                if (retInfo == null)
                {
                    throw new Exception("resInfo is null");
                }
                if (!retInfo.Success)
                {
                    throw new Exception($"Success:{retInfo.Success},Desc:{retInfo.Desc},Details:{retInfo.Details}");
                }
                List<VinQueryResResult> retResults = ret.Result;

                //調用存OTS
                string otsStr = JsonConvert.SerializeObject(retResults);
                //if (NeedSaveOTS())
                //{
                //    SaveOTS(otsStr);
                //}

                if (retResults != null && retResults.Count > 0)
                {
                    result = retResults[0];
                }
            }
            catch (Exception ex)
            {
                LoggerManager.Logger.LogError($"LiYang Api ex: {ex.Message}");
            }

            return result;
        }
        private static string GetVinUrl(string vin)
        {
            string url = "http://service.vin114.net/req/LevelData?callback=&xmlInput=";
            string param = $"<root><appkey>{_appKey}</appkey><appsecret>{_appSecret}</appsecret><method>level.vehicle.vin.get</method><requestformat>json</requestformat><vin>{vin}</vin></root>";
            return $"{url}{HttpUtility.UrlEncode(param)}";
        }
        private static bool NeedSaveOTS()
        {
            bool needSave;
            bool.TryParse(ConfigurationManager.Settings.Variables["LiYang.NeedSaveOTS"], out needSave);
            return needSave;
        }

        private static void SaveOTS(string obj)
        {

        }
    }
    #region models
    public class VinQueryRes
    {
        public List<VinQueryResResult> Result { get; set; }
        public VinQueryResInfo Info { get; set; }
    }
    public class VinQueryResInfo
    {
        public bool Success { get; set; }
        public string Desc { get; set; }
        public string Error { get; set; }
        public int? Total { get; set; }
        public int? Records { get; set; }
        public string Power { get; set; }
        public string Details { get; set; }
    }
    public class VinQueryResResult
    {
        public string Manufacturers { get; set; }
        public string Brand { get; set; }
        public string Series { get; set; }
        public string Models { get; set; }
        public string SalesName { get; set; }
        public string Year { get; set; }
        public string EmissionStandard { get; set; }
        public string VehicleType { get; set; }
        public string GuidingPrice { get; set; }
        public string ListingYear { get; set; }
        public string ListingMonth { get; set; }
        public string ProducedYear { get; set; }
        public string IdlingYear { get; set; }
        public string ProductionStatus { get; set; }
        public string Country { get; set; }
        public string VehicleAttributes { get; set; }
        public string EngineModel { get; set; }
        public string CylinderVolume { get; set; }
        public string Displacement { get; set; }
        public string Induction { get; set; }
        public string FuelType { get; set; }
        public string FuelGrade { get; set; }
        public string Horsepower { get; set; }
        public string PowerKw { get; set; }
        public string CylinderArrangement { get; set; }
        public string Cylinders { get; set; }
        public string ValvesPerCylinder { get; set; }
        public string TransmissionType { get; set; }
        public string TransmissionDescription { get; set; }
        public string GearNumber { get; set; }
        public string EngineLocation { get; set; }
        public string DriveMode { get; set; }

        //extra
        public string vin { get; set; }
        public string selectorId { get; set; }
        public string brandCode { get; set; }
    }

    #endregion
}
